// export const baseUrl = 'http://feitu.cn/api/';
export const baseUrl = 'https://feitu.smartspark.xyz/api/';

function httpRequest(obj) {
    let token = uni.getStorageSync('token')
    return new Promise((resolve, reject)=> {
        uni.request({
			url: obj.url,
			data: obj.data,
			method: obj.method,
			header: {
				"Content-Type": "application/json",
				token: token,
				apptype: 'merchant_xcc',
			},
			dataType: 'json',
		}).then((response) => {
			// 跳转首页
			if(response.statusCode === 401){
				uni.clearStorageSync();
				uni.switchTab({url:'/'});
				reject(new Error('Unauthorized'));
				return;
			}
			if(response.statusCode !== 200){
				uni.showToast({title: '请求失败，请稍后重试！', icon:'none'});
				reject(new Error('Request failed'));
				return
			}
			
			const data = response.data;
			// 跳转首页，重新登录
			if(data.code==401){
				uni.clearStorageSync();
				let pages = getCurrentPages();
				let page = (pages[pages.length - 1]).route;
				// uni.setStorageSync('cur_page', page)
				uni.switchTab({url:'/pages/user/user'});
				reject(new Error('Unauthorized'));
				return
			}
			if(data.code==1){
				resolve(data.data)
			}else{
				uni.showToast({title: data.info, icon:'none'});
				reject(new Error(data.info));
				return
			}
        }).catch((error) => {
			reject(error)
		})
    }) 
};

export const get = (url) =>  httpRequest({
	url: baseUrl + url,
	data: {},
	method: 'GET'
})

export const post = (url, data) =>  httpRequest({
	url: baseUrl + url,
	data: data,
	method: 'POST'
})


export default {
	 baseUrl,
	    get,
	    post,
}